//
//  CedarCameraTools.m
//  CedarFinancialPlanner
//
//  Created by lshenrong on 2018/6/14.
//  Copyright © 2018年 cedarhd. All rights reserved.
//

#import "CedarCameraTools.h"

#import "CedarCameraTools.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
//#import <RSKImageCropViewController.h>

@interface CedarCameraTools()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,
                                UIGestureRecognizerDelegate>


@property (nonatomic,weak) UIViewController *parentViewController;
@property (nonatomic,strong) UIImagePickerController *imagePickController;
@property (nonatomic,strong) UIAlertController *alertController;

@end


@implementation CedarCameraTools

+ (instancetype)cameraWithViewController:(UIViewController *)vc{
    CedarCameraTools *camera = [[CedarCameraTools alloc]init];
    if (camera) {
        if(!vc){
           vc = [PlatformTools getCurrentViewController];
        }
        camera.parentViewController =  vc;
    }
    return camera;
}

- (instancetype)initWithViewController:(UIViewController *)vc{
    if (self = [super init]) {
        if(!vc){
            vc = [PlatformTools getCurrentViewController];
        }
        self.parentViewController =  vc;
    }
    return self;
}



- (void)dealloc{
    
}


#pragma mark -  camera actin

- (void)showTakePicture{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    self.alertController = alertController;
    UIAlertAction *photoAlbumAction = [UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
            if(PHAuthorizationStatusAuthorized == status){
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self showPhotosAlbum];
                });
            }else{
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSString *appName = [PlatformTools appName];
                    NSString *tips = [NSString stringWithFormat:@"您还未开启%@照片授权,不能使用该功能。请到“设置-%@-照片”中开启",appName,appName];
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"照片未授权" message:tips preferredStyle:UIAlertControllerStyleAlert];
                    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    }]];
                    [alert addAction:[UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        NSURL *appSettings = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                        [[UIApplication sharedApplication] openURL:appSettings];
                    }]];
                    [self.parentViewController presentViewController:alert animated:YES completion:nil];
                });
            }
        }];
        
    }];
    
    UIAlertAction *cemeraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {//相机权限
            dispatch_async(dispatch_get_main_queue(), ^{
                if (granted) {
                    [self showCamera];
                }else{
                    NSString *appName = [PlatformTools appName];
                    NSString *tips = [NSString stringWithFormat:@"您还未开启%@相机授权,不能使用该功能。请到“设置-%@-相机”中开启",appName,appName];
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"相机未授权" message:tips preferredStyle:UIAlertControllerStyleAlert];
                    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        
                    }]];
                    [alert addAction:[UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        NSURL *appSettings = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                        [[UIApplication sharedApplication] openURL:appSettings];
                    }]];
                   [self.parentViewController presentViewController:alert animated:YES completion:nil];
                }
            });
            
        }];
        
    }];
    

    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

       }];
    @try {
        [photoAlbumAction setValue:[UIColor colorWithHexString:@"#333333"] forKey:@"_titleTextColor"];
        [cemeraAction setValue:[UIColor colorWithHexString:@"#333333"] forKey:@"_titleTextColor"];
        [cancleAction setValue:[UIColor colorWithHexString:@"#333333"] forKey:@"_titleTextColor"];
    } @catch (NSException *exception) {
        CLog(@"%@",exception);
    }
  
    [alertController addAction:cemeraAction];
    [alertController addAction:photoAlbumAction];
    [alertController addAction:cancleAction];
    [self.parentViewController presentViewController:alertController animated:YES completion:nil];
}

- (void)showCamera{
    self.imagePickController.sourceType = UIImagePickerControllerSourceTypeCamera;
    [self.parentViewController presentViewController:self.imagePickController animated:YES completion:nil];
}

- (void)showPhotoLibrary{
    self.imagePickController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self.parentViewController presentViewController:self.imagePickController animated:YES completion:nil];
}

- (void)showPhotosAlbum{
    self.imagePickController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    [self.parentViewController presentViewController:self.imagePickController animated:YES completion:nil];
}

#pragma mark -- UIImagePickerControllerDelegate

- (CGSize)toCompressSize:(CGSize)sourceSize{
    CGFloat ratio = SCREEN_WIDTH*2;
    if (sourceSize.width > ratio) {
        float compressedRatio = ratio / sourceSize.width;
        CGFloat width =  sourceSize.width * compressedRatio;
        CGFloat hieght = sourceSize.height *compressedRatio;
        return CGSizeMake(width, hieght);
    }
    return sourceSize;
}

//2.保持原来的长宽比，生成一个缩略图
- (UIImage *)thumbnailWithImageWithoutScale:(UIImage *)image size:(CGSize)asize{
    UIImage *newimage;
    if (nil == image) {
        newimage = nil;
    }
    else{
        CGSize oldsize = image.size;
        CGRect rect;
        if (asize.width/asize.height > oldsize.width/oldsize.height) {
            rect.size.width = asize.height*oldsize.width/oldsize.height;
            rect.size.height = asize.height;
            rect.origin.x = (asize.width - rect.size.width)/2;
            rect.origin.y = 0;
        }
        else{
            rect.size.width = asize.width;
            rect.size.height = asize.width*oldsize.height/oldsize.width;
            rect.origin.x = 0;
            rect.origin.y = (asize.height - rect.size.height)/2;
        }
        UIGraphicsBeginImageContext(asize);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
        UIRectFill(CGRectMake(0, 0, asize.width, asize.height));//clear background
        [image drawInRect:rect];
        newimage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    return newimage;
}

//大于多少kb的图片需要压缩
- (NSData*)dataCompressedImageToLimitSizeOfKB:(CGFloat)kb image:(UIImage*)image{
    if(!image){
        return nil;
    }
    NSData * imageData = UIImageJPEGRepresentation(image,1);
    NSUInteger length = [imageData length] /1024;
#ifdef DEBUG
    NSLog(@"压缩前大小imageData = %zdK，size %@",length, NSStringFromCGSize(image.size));
#endif
    if(length >kb ){
        float compressedRatio = kb / length;
        return UIImageJPEGRepresentation(image, compressedRatio);
        
    }else{
        return imageData;
    }
}

/*
- (void)saveImage:(UIImage *)image{

    //png格式
    
    NSData *imagedata= UIImageJPEGRepresentation(image,1);
    
    //JEPG格式
    
    //NSData *imagedata=UIImageJEPGRepresentation(m_imgFore,1.0);

    
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    
    NSString *documentsDirectory = [paths objectAtIndex:0];
    
    
    NSString *savedImagePath=[documentsDirectory stringByAppendingPathComponent:@"saveTest.jpg"];

    [imagedata writeToFile:savedImagePath atomically:YES];
}
*/

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo{
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    if(image){
        CGFloat fixelW = CGImageGetWidth(image.CGImage);
        CGFloat fixelH = CGImageGetHeight(image.CGImage);
#if DEBUG
        NSLog(@"%@",[NSThread currentThread]);
        NSString *wStr =  [NSString stringWithFormat:@"%.0f",fixelW];
        NSString *hStr =  [NSString stringWithFormat:@"%.0f",fixelH];
        CLog(@"Picker size: %@,w:%@,h:%@",NSStringFromCGSize(image.size),wStr,hStr);
#endif
        NSData *imageData =  [self dataCompressedImageToLimitSizeOfKB:1024 image:image];
        @weakify(self)
        if(self.photoSelectBlock){
            @strongify(self)
            CGSize size = CGSizeMake(fixelW, fixelH);
            self.photoSelectBlock(imageData,size,self.tag);
        }
    }
    [self.imagePickController dismissViewControllerAnimated:YES completion:nil];
}

// 取消选择照片:
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    CLog(@"取消图片选择");
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (UIImagePickerController *)imagePickController{
    if (!_imagePickController) {
        _imagePickController = [[UIImagePickerController alloc] init];//初始化
        _imagePickController.delegate = self;
       // _imagePickController.allowsEditing = YES;
    }
    return _imagePickController;
}

@end

